﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using PortalWeb.Core.Entity;
using PortalWeb.Service;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using PortalWeb.Areas.Admin.Models;
using PortalWeb.Filter;
using System.ComponentModel;
using PortalWeb.Business.Manager;
using PortalWeb.Core.IManager;
using PortalWeb.Common.UI;

namespace PortalWeb.Areas.Admin.Controllers
{
    [Navbar("角色管理", "系统管理")]
    [CustomAuthorize]
    public class RoleController : Controller
    {
        private ApplicationRoleManager _roleManager;
        private IFunctionManager _systemFunctionManager;

        public RoleController(IFunctionManager systemFunctionManager)
        {
            _systemFunctionManager = systemFunctionManager;
        }

        public IFunctionManager FunctionManager
        {
            get { return _systemFunctionManager ?? HttpContext.GetOwinContext().GetUserManager<IFunctionManager>(); }
            private set { _systemFunctionManager = value; }
        }
        public ApplicationRoleManager RoleManager
        {
            get { return _roleManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationRoleManager>(); }
            private set { _roleManager = value; }
        }

        // GET: Admin/Role
        public ActionResult Index()
        {
            return View();
        }

        [CustomAuthorize]
        public async Task<JsonResult> List(string sort = "Id", string order = "", int offset = 0, int limit = 10,
            string search = "")
        {
            var model = from p in await RoleManager.LoadPageEntitiesnAsync<ApplicationRole>(
                f => f.Name.Contains(search) || f.Describe.Contains(search),
                order, sort, offset, limit)
                select new EditRoleViewModel()
                {
                    Name = p.Name,
                    Describe = p.Describe,
                    Id = p.Id
                };
            return Json(new {total = RoleManager.Count(), rows = model},
                JsonRequestBehavior.AllowGet);
        }


        //
        // GEG: /Account/Edit
        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        public ActionResult Edit(string id, ManageMessageId? message = null)
        {
            var role = RoleManager.Roles.First(u => u.Id == id);
            var model = new EditRoleViewModel()
            {
                Name = role.Name,
                Describe = role.Describe,
                Id = role.Id
            };
            ViewBag.MessageId = message;
            return View(model);
        }


        [HttpPost]
        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit(EditRoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {

                    var role = RoleManager.Roles.Single(p => p.Id == model.Id);
                    role.Name = model.Name;
                    role.Describe = model.Describe;
                    foreach (var pid in model.Functions.Split(','))
                    {
                        if (string.IsNullOrEmpty(pid))
                        {
                            break;
                        }
                        var id = int.Parse(pid);

                        var f = await FunctionManager.GetAsync(id);
                        role.Functions.Add(f);
                    }
                    var result = await RoleManager.UpdateAsync(role);
                    if (result.Succeeded)
                    {
                        string url = Url.Action("Index");
                        return Json(new {success = true, url});
                    }
                    AddErrors(result);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }
            return View(model);
        }

        //
        // GEG: /Account/Delete
        [Authorize(Roles = RoleConst.ADMINISTRATOR)]
        public ViewResult Delete(string id, ManageMessageId? message)
        {
            var role = RoleManager.Roles.First(u => u.Id == id);
            var model = new EditRoleViewModel()
            {
                Name = role.Name,
                Describe = role.Describe,
                Id = role.Id
            };
            return View(model);
        }

        private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
        }
    }
}